<?php

use console\db\Migration;
use yii\db\Query;
use yii\helpers\ArrayHelper;

/**
 * 短视频评论信息转移
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000007_t_sns_dynamic_comment_append extends Migration {

    /**
     * @inheritdoc
     */
    public $sequenceTableName = 'sns_dynamic_comment';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $db = Yii::$app->olddb;
        $query = (new Query())->from('{{%member_comments}}')
        ->where(['model' => 'videos'])
        ->orderBy([
            'model_id' => SORT_ASC,
            'created_at' => SORT_ASC
        ]);
        $this->handleProgress($query, [$this, 'evenDule'], null, $db);
    }

    /**
     * @inheritdoc
     */
    public function filterData(&$data) {
        if (!parent::validateTransfer($data)) {
            return false;
        }
        if (!$data['model_id'] || $data['status'] < 0 || $data['deleted_at']) {
            return false;
        }
        $message = str_ireplace(['INSERT INTO', 'script'], '', $data['content']);
        if ($message !== $data['content']) {
            return false;
        }
        $message = trim(strip_tags($message));
        if (!$message) {
            return false;
        }
        $data['content'] = $message;

        $dynamicid = (new Query())->from('{{%sns_dynamic_video}}')->select('dynamic_id')->where([
            'video_id' => $data['model_id'],
            'deleted_at' => 0,
        ])->scalar();

        if (!$dynamicid) {
            return false;
        }
        $data['dynamic_id'] = $dynamicid;

        return true;
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        $connect = $migration->db->createCommand();
        $items = [];
        foreach ($rows as $row) {
            if (!$migration->filterData($row)) {
                continue;
            }
            $items[] = [
                'user_id' => $row['uid'],
                'dynamic_id' => $row['dynamic_id'],
                'post' => $row['content'],
                'status' => 10,
                'created_at' => strtotime($row['created_at']),
                'updated_at' => strtotime($row['updated_at']),
            ];
        }
        if (empty($items)) {
            return;
        }
        $connect->batchInsert('{{%sns_dynamic_comment}}', [
            'user_id',
            'dynamic_id',
            'post',
            'status',
            'created_at',
            'updated_at',
        ], $items)->execute();
    }

}
